package com.heima.comment.service.impl;
import java.math.BigDecimal;
import java.util.*;

import com.aliyuncs.ram.model.v20150501.CreateUserRequest;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.comment.service.CommentRepayService;
import com.heima.common.exception.CustomException;
import com.heima.feigns.user.UserFeign;
import com.heima.model.comment.dtos.CommentRepayDto;
import com.heima.model.comment.dtos.CommentRepayLikeDto;
import com.heima.model.comment.dtos.CommentRepaySaveDto;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vos.ApCommentRepayVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;


/**
 *
 */
@Service
public class CommentRepayServiceImpl implements CommentRepayService {

    @Autowired
    UserFeign userFeign;

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    // 加载评论回复信息
    public ResponseResult loadCommentRepay(CommentRepayDto dto) {
        if (dto == null || dto.getCommentId() == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (dto.getMinDate() == null){
            dto.setMinDate(new Date());
        }
        if (dto.getSize() == null || dto.getSize() == 0 || dto.getSize() >= 100){
            dto.setSize(10);
        }
        ApUser apUser = AppThreadLocalUtils.getUser();
        // 根据评论id以及创建时间小于最小时间查询回复列表，按照创建时间降序排序
        Query limit = Query.query(Criteria.where("commentId").is(dto.getCommentId())
                .and("createdTime").lt(dto.getMinDate()))
                .with(Sort.by(Sort.Direction.DESC, "createdTime"))
                .limit(dto.getSize());
        List<ApCommentRepay> apCommentRepays = mongoTemplate.find(limit, ApCommentRepay.class);
        // 如果用户没有登陆直接返回结果
        if (apUser == null){
            return ResponseResult.okResult(apCommentRepays);
        }else {
            // 获取当前用户
            ApUser user = userFeign.findUserById(Long.valueOf(apUser.getId()));
            if (user == null){
                throw new CustomException(AppHttpCodeEnum.USER_NOT_EXIST,"用户信息不存在");
            }
            // 遍历回复信息
            Query myApCommentRepayListQuery = Query.query(Criteria.where("commentId").is(dto.getCommentId())
                    .and("authorId").is(user.getId()));
            List<ApCommentRepay> myApCommentRepayList = mongoTemplate.find(myApCommentRepayListQuery, ApCommentRepay.class);
            ArrayList<ApCommentRepayVo> apCommentRepayVos = new ArrayList<>();
            for (ApCommentRepay apCommentRepay : myApCommentRepayList) {
                ApCommentRepayVo apCommentRepayVo = new ApCommentRepayVo();
                BeanUtils.copyProperties(apCommentRepay,apCommentRepayVo);
                // 用每一个回复的id去点赞列表中查询
                String apCommentRepayId = apCommentRepay.getId();
                Query query = Query.query(Criteria.where("commentRepayId").is(apCommentRepayId)
                        .and("operation").is(0));
                ApCommentRepayLike apCommentRepayLike
                        = mongoTemplate.findOne(query, ApCommentRepayLike.class);
                if (apCommentRepayLike != null){
                    apCommentRepayVo.setOperation((short) 0);
                }
                apCommentRepayVos.add(apCommentRepayVo);
            }
            return ResponseResult.okResult(apCommentRepayVos);
        }
    }

    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDto dto) {
        if (dto == null || dto.getCommentId() == null || dto.getContent() == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 获取用户登陆信息
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null){
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN,"请先登陆");
        }
        ApUser apUser = userFeign.findUserById(Long.valueOf(user.getId()));
        if (apUser == null){
            throw new CustomException(AppHttpCodeEnum.USER_NOT_EXIST,"用户不存在");
        }
        // 阿里云不用测了,他们不敢
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(apUser.getId());
        apCommentRepay.setAuthorName(apUser.getName());
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setLikes(0);
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());

        mongoTemplate.insert(apCommentRepay);

        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        apComment.setReply(apComment.getReply() + 1);
        mongoTemplate.save(apComment);

        return ResponseResult.okResult();
    }

    @Override
    // 保存回复点赞
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDto dto) {
        // 检查参数
        if(dto == null || dto.getCommentRepayId() == null || dto.getOperation() == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //根据评论回复id查询评论回复信息
        ApUser apUser = AppThreadLocalUtils.getUser();
        if (apUser == null){
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN,"请先登陆后点赞");
        }
        ApCommentRepay apCommentRepay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);
        int likes = 0;
        if (apCommentRepay != null && dto.getOperation() == 0){
            // 评论信息点赞加一
            likes = apCommentRepay.getLikes() + 1;
            mongoTemplate.save(apCommentRepay);

            // 保存点赞信息,如果已经点过赞不能重复点赞
            Query query = Query.query(Criteria.where("authorId").is(apUser.getId())
                    .and("commentRepayId").is(dto.getCommentRepayId()));
            ApCommentRepayLike apCommentRepayLike = mongoTemplate.findOne(query, ApCommentRepayLike.class);
            if (apCommentRepayLike != null){
                throw new CustomException(AppHttpCodeEnum.DATA_EXIST,"不能重复点赞");
            }
            apCommentRepayLike = new ApCommentRepayLike();
            apCommentRepayLike.setAuthorId(apUser.getId());
            apCommentRepayLike.setCommentRepayId(dto.getCommentRepayId());
            apCommentRepayLike.setOperation((short)0);
            mongoTemplate.save(apCommentRepayLike);
        }
        if (apCommentRepay != null && dto.getOperation() == 1){
            // 评论信息点赞减一
            likes = apCommentRepay.getLikes() - 1;
            mongoTemplate.save(apCommentRepay);

            // 删除点赞信息

            Query query = Query.query(Criteria.where("authorId").is(apUser.getId())
                    .and("commentRepayId").is(dto.getCommentRepayId()));
            ApCommentRepayLike apCommentRepayLike = mongoTemplate.findOne(query, ApCommentRepayLike.class);
            mongoTemplate.remove(apCommentRepayLike);
        }

        // 返回数据
        Map map = new HashMap();
        map.put("likes",likes);
        return ResponseResult.okResult(map);

    }
}
